package com.ycy;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.Set;

public class ValidateDemo {

    private static final ValidatorFactory VALIDATOR_FACTORY = Validation.buildDefaultValidatorFactory();

    /**
     * 参数校验
     *
     * @param paramObject 需要校验的参数
     */
    public static void validateObject(Object paramObject) {
        Validator validator = VALIDATOR_FACTORY.getValidator();
        Set<ConstraintViolation<Object>> validateResult = validator.validate(paramObject);
        if (validateResult.isEmpty())
            return;

        StringBuilder errorMessageSb = new StringBuilder();
        for (
                ConstraintViolation<Object> violation : validateResult) {
            errorMessageSb.append(violation.getMessage()).append(";");
        }
        System.out.println(errorMessageSb);
    }

    public static void main(String[] args) {

        Product product = new Product();
        product.setId(1L);
        product.setProductName("john@example.com");
//        product.setPrice(0.2F);

        validateObject(product);

    }

}
